from d2l import torch as d2l
import regex as re
import collections

# 预处理的主要步骤：
# 1. 将文本作为字符串加载到内存中
# 2. 将字符串拆分为词元 - 单词/字符
# 3. 建立词表，将词元映射成数字索引
# 4. 文本索引 -> 数字索引，方便模型操作

# 读取数据
d2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt',
                                '090b5e7e70c295757f55df93cb0a180b9691891a')


# 读取数据
def read_time_machine():
    """加载数据集"""
    with open(d2l.download('time_machine'), 'r') as f:
        lines = f.readlines()
    return [re.sub('[^A-Za-z]+', ' ', line).strip().lower() for line in lines]


# 词元化
def tokenize(lines, token='word'):
    """将文本拆分成词元"""
    if token == 'word':
        return [line.split() for line in lines]
    elif token == "char":
        return [list(line) for line in lines]
    else:
        print('错误：未知词元类型：' + token)


def count_corpus(tokens):
    """统计词元的频率"""
    # 这里的tokens是1D列表或2D列表
    if len(tokens) == 0 or isinstance(tokens[0], list):
        # 将词元列表展平成一个列表
        tokens = [token for line in tokens for token in line]
    return collections.Counter(tokens)


# 整合词表
class Vocab:
    """文本词表"""
    def __init__(self, tokens = None, min_freq = 0, reserved_tokens=None):
        if tokens is None:
            tokens = []
        if reserved_tokens is None:
            reserved_tokens = []

        # 根据出现频率排序
        counter = count_corpus(tokens)
        self._token_freqs = sorted(counter.items(), key=lambda x: x[1],
                                   reverse=True)

        # 未知词元的索引为 0
        self.idx_to_token = ['<unk>'] + reserved_tokens
        self.token_to_idx = {token: idx for idx, token in enumerate(self.idx_to_token)}
        for token, freq in self._token_freqs:
            if freq < min_freq:
                break
            if token not in self.token_to_idx:
                self.idx_to_token.append(token)
            self.token_to_idx[token] = len(self.idx_to_token) - 1

    def __len__(self):
        return len(self.idx_to_token)

    def __getitem__(self, tokens):
        if not isinstance(tokens, (list, tuple)):
            return self.token_to_idx.get(tokens, self.unk)
        return [self.__getitem__(token) for token in tokens]

    def to_tokens(self, indices):
        if not isinstance(indices, (list, tuple)):
            return self.idx_to_token[indices]
        return [self.idx_to_token[index] for index in indices]

    def unk(self):
        """未知词元的索引为0"""
        return 0

    def token_freqs(self):
        return self._token_freqs


# merge 词元和词表
def load_corpus_time_machine(max_tokens=-1):
    lines = read_time_machine()
    tokens = tokenize(lines, 'char')
    vocab = Vocab(tokens)
    corpus = [vocab[token] for line in tokens for token in line]
    if max_tokens > 0:
        corpus = corpus[:max_tokens]
    return corpus, vocab


if __name__ == "__main__":
    # 读取相应的数据集
    lines = read_time_machine()
    print(f'# 文本总行数: {len(lines)}')
    print(lines[0])
    print(lines[10])

    # 打印词元
    tokens = tokenize(lines)
    for i in range(11):
        print(tokens[i])

    # 打印词表
    vocab = Vocab(tokens)
    print(list(vocab.token_to_idx.items())[:10])

    # 文本转换为索引
    for i in [0, 10]:
        print('文本:', tokens[i])
        print('索引:', vocab[tokens[i]])

    # 打印处理词表和词元长度
    corpus, vocab = load_corpus_time_machine()
    print(len(corpus)), print(len(vocab))


